﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace Rtl.SharePoint.Administration
{
    /// <summary>
    /// Helper class to persist Virtual Earth connection information in the hierarchical object store.
    /// </summary>
    internal sealed class VEConnectionInfoStorage
    {
        // hierarchical object store data storage information
        private const string VE_STOR_CON_ID = "{5464B164-6120-44ff-BCD2-C522F9E572A7}";
        private const string VE_STOR_CON_NAME = "Rtl.SharePoint.Administration.VEConnectionInfo";

        private VEConnectionInfo _settings = null;

        /// <summary>
        /// Updates settings in the hierarchcal object store
        /// </summary>
        public void Update()
        {
            if (_settings != null)
                _settings.Update(true);
        }

        /// <summary>
        /// Virtual Earth service connection settings.
        /// </summary>
        public VEConnectionInfo Settings
        {
            get
            {
                // have the settings already been loaded?
                if (_settings == null)
                {
                    // settings have not been loaded, get them
                    LoadSettings();
                }

                return _settings;
            }
        }

        /// <summary>
        /// Retrieve the settings from the hiearchical object store.
        /// </summary>
        private void LoadSettings()
        {
            SPFarm f = null;
            try
            {
                // get the settings as a child of the farm object
                f = SPFarm.Local;
                _settings = f.GetChild<VEConnectionInfo>(VE_STOR_CON_NAME);

                if (_settings == null)
                {
                    // settings did not exist, create them
                    _settings = new VEConnectionInfo(VE_STOR_CON_NAME, f, new Guid(VE_STOR_CON_ID));
                }
            }
            finally
            {
                // release the reference to the parent object
                IDisposable disposable = f as IDisposable;
                if (disposable != null)
                    disposable.Dispose();
            }
        }
    }
}
